<!--components/canvas-drag/index.wxml-->
<template>
	<canvas canvas-id="canvas-label"
	:disable-scroll="true"
	:bindtouchstart="start"
	:bindtouchmove="move"
	:bindtouchend="end"
	:style="'width: ' + width + 'rpx; height: ' + height + 'rpx;'"></canvas>
</template>
<script>
import dragGraph from '@/util/dragGraph'
export default{
	data() {
		return {
			
		}
	},
	props: {
	  /**
	   * 组件的属性列表
	   */
		graph: {
		  type: Object,
		  value: {},
		  observer: 'onGraphChange',
		},
		bgColor: {
		  type: String,
		  value: '',
		},
		bgImage: {
		  type: String,
		  value: '',
		},
		bgSourceId: {
		  type: String,
		  value: '',
		},
		width: {
		  type: Number,
		  value: 750,
		},
		height: {
		  type: Number,
		  value: 750,
		}
	 },
	/**
	 * 组件的方法列表
	 */
	created() {
	  const sysInfo = uni.getSystemInfoSync();
	  const screenWidth = sysInfo.screenWidth;
	  this.factor = screenWidth / 750;
	
	  if (typeof this.drawArr === 'undefined') {
		this.drawArr = [];
	  }
	  this.ctx = uni.createCanvasContext('canvas-label', this);
	  this.draw();
	},
	methods: {
	  toPx(rpx) {
		return rpx * this.factor;
	  },
	  onGraphChange(n, o) {
		if (JSON.stringify(n) === '{}') return;
		this.drawArr.push(new dragGraph(Object.assign({
		  x: 30,
		  y: 30,
		}, n), this.ctx, this.factor));
		this.draw();
	  },
	  initByArr(newArr) {
		this.drawArr = [];
		// 循环插入 drawArr
		newArr.forEach((item, index) => {
		  switch (item.type) {
			case 'bgColor':
			  this.bgImage = '';
			  this.bgSourceId = '';
			  this.bgColor = item.color;
			  break;
			case 'bgImage':
			  this.bgColor = '';
			  this.bgImage = item.url;
			  if (item.sourceId) {
				this.bgSourceId = item.sourceId;
			  }
			  break;
			case 'image':
			case 'text':
			  if (index === newArr.length - 1) {
				item.selected = true;
			  } else {
				item.selected = false;
			  }
			  this.drawArr.push(new dragGraph(item, this.ctx, this.factor));
			  break;
		  }
	
		});
		this.draw();
	  },
	  draw() {
		  console.log(this.bgImage)
		if (this.bgImage !== '') {
		  this.ctx.drawImage(this.bgImage, 5, 0, 191, 384);
		}
		if (this.bgColor !== '') {
		  this.ctx.save();
		  this.ctx.setFillStyle(this.bgColor);
		  this.ctx.fillRect(0, 0, this.toPx(this.width), this.toPx(this.height));
		  this.ctx.restore();
		}
		this.drawArr.forEach((item) => {
		  item.paint();
		});
		return new Promise((resolve) => {
		  this.ctx.draw(false, () => {
			resolve();
		  });
		});
	  },
	  start(e) {
		const {
		  x,
		  y
		} = e.touches[0];
		this.tempGraphArr = [];
		let lastDelIndex = null; // 记录最后一个需要删除的索引
		this.drawArr && this.drawArr.forEach((item, index) => {
		  const action = item.isInGraph(x, y);
		  if (action) {
			item.action = action;
			this.tempGraphArr.push(item);
			// 保存点击时的坐标
			this.currentTouch = {
			  x,
			  y
			};
			if (action === 'del') {
			  lastDelIndex = index; // 标记需要删除的元素
			}
		  } else {
			item.action = false;
			item.selected = false;
		  }
		});
		// 保存点击时元素的信息
		if (this.tempGraphArr.length > 0) {
		  for (let i = 0; i < this.tempGraphArr.length; i++) {
			let lastIndex = this.tempGraphArr.length - 1;
			// 对最后一个元素做操作
			if (i === lastIndex) {
			  // 未选中的元素，不执行删除和缩放操作
			  if (lastDelIndex !== null && this.tempGraphArr[i].selected) {
				if (this.drawArr[lastDelIndex].action === 'del') {
				  this.drawArr.splice(lastDelIndex, 1);
				  this.ctx.clearRect(0, 0, this.toPx(this.width), this.toPx(this.height));
				}
			  } else {
				this.tempGraphArr[lastIndex].selected = true;
				this.currentGraph = Object.assign({}, this.tempGraphArr[lastIndex]);
			  }
			} else {
			  // 不是最后一个元素，不需要选中，也不记录状态
			  this.tempGraphArr[i].action = false;
			  this.tempGraphArr[i].selected = false;
			}
		  }
		}
		this.draw();
	  },
	  del(index) {
		this.drawArr.splice(index, 1);
	  },
	  move(e) {
		const {
		  x,
		  y
		} = e.touches[0];
		if (this.tempGraphArr && this.tempGraphArr.length > 0) {
		  const currentGraph = this.tempGraphArr[this.tempGraphArr.length - 1];
		  if (currentGraph.action === 'move') {
			currentGraph.centerX = this.currentGraph.centerX + (x - this.currentTouch.x);
			currentGraph.centerY = this.currentGraph.centerY + (y - this.currentTouch.y);
			// 使用中心点坐标计算位移，不使用 x,y 坐标，因为会受旋转影响。
			if (currentGraph.type !== 'text') {
			  currentGraph.x = currentGraph.centerX - this.currentGraph.w / 2;
			  currentGraph.y = currentGraph.centerY - this.currentGraph.h / 2;
			}
		  } else if (currentGraph.action === 'transform') {
			currentGraph.transform(this.currentTouch.x, this.currentTouch.y, x, y, this.currentGraph);
		  }
		  // 更新4个坐标点（相对于画布的坐标系）
		  currentGraph._rotateSquare();
		  alpha = 0.7;
		  source = "source-over";
		  // console.log('移动')
	
		  this.draw();
		}
	  },
	  end(e) {
		this.tempGraphArr = [];
	  },
	  export () {
		return new Promise((resolve, reject) => {
		  this.drawArr = this.drawArr.map((item) => {
			item.selected = false;
			return item;
		  });
		  this.draw().then(() => {
			uni.canvasToTempFilePath({
			  canvasId: 'canvas-label',
			  success: (res) => {
				resolve(res.tempFilePath);
			  },
			  fail: (e) => {
				reject(e);
			  },
			}, this);
		  });
		})
	  },
	  delItem(index) {
		this.del(index);
	  },
	  exportJson() {
		return new Promise((resolve, reject) => {
		  let exportArr = this.drawArr.map((item) => {
			item.selected = false;
			switch (item.type) {
			  case 'image':
				return {
				  type: 'image',
				  url: item.fileUrl,
				  y: item.y,
				  x: item.x,
				  w: item.w,
				  h: item.h,
				  rotate: item.rotate,
				  sourceId: item.sourceId,
				};
				break;
			  case 'text':
				return {
				  type: 'text',
				  text: item.text,
				  color: item.color,
				  fontSize: item.fontSize,
				  fontFamily: item.fontFamily,
				  y: item.y,
				  x: item.x,
				  w: item.w,
				  h: item.h,
				  rotate: item.rotate,
				};
				break;
			}
		  });
		  if (this.bgImage) {
			let tmp_img_config = {
			  type: 'bgImage',
			  url: this.bgImage,
			};
			if (this.bgSourceId) {
			  tmp_img_config['sourceId'] = this.bgSourceId;
			}
			exportArr.unshift(tmp_img_config);
		  } else if (this.bgColor) {
			exportArr.unshift({
			  type: 'bgColor',
			  color: this.bgColor
			});
		  }
	
		  resolve(exportArr);
		})
	  },
	  changFont(font) {
		const selected = this.drawArr.filter((item) => item.selected);
		if (selected.length > 0) {
		  // console.log(selected[0])
		  selected[0].fontFamily = font;
		}
		this.draw();
	  },
	  changColor(color) {
		const selected = this.drawArr.filter((item) => item.selected);
		if (selected.length > 0) {
		  selected[0].color = color;
		}
		this.draw();
	  },
	  changeBgColor(color) {
		this.bgImage = '';
		this.bgColor = color;
		this.draw();
	  },
	  changeBgImage(newBgImg) {
		this.bgColor = '';
		if (typeof newBgImg == 'string') {
		  this.bgSourceId = '';
		  this.bgImage = newBgImg;
		} else {
		  this.bgSourceId = newBgImg.sourceId;
		  this.bgImage = newBgImg.url;
		}
		this.draw();
	  },
	  clearCanvas() {
		this.ctx.clearRect(0, 0, this.toPx(this.width), this.toPx(this.height));
		this.ctx.draw();
		this.drawArr = [];
		this.bgColor = '';
		this.bgSourceId = '';
		this.bgImage = '';
	  }
	}
}
</script>
<style>
	.movable-label {
	  margin-top: 300rpx;
	  width: 750rpx;
	  height: 400rpx;
	  background: #eee;
	}
	.movable-block {
	    width: 120rpx;
	    height: 120rpx;
	    background: #ccc;
	}
	.movable-block .image-con {
	    width: 100%;
	    height: 100%;
	}
</style>